package com.zdp.chat.config.socket;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import io.netty.channel.Channel;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class SocketClient {


    @Value("${hf.chat.maxChannelNum:10000}")
    private Integer maxChannelNum;

    private final static String SOCKET_CACHE_KEY = "socket:cache:%s";

    Cache<String, Channel> lfuCache;

    @PostConstruct
    public void init() {
        this.lfuCache = CacheUtil.newLFUCache(maxChannelNum);
        log.info("云消息chanel缓存客户端初始化成功,channel最大存储个数:{}", maxChannelNum);
    }

    private static String key(String uid) {
        return String.format(SOCKET_CACHE_KEY, uid);
    }

    public void put(String uid, Channel channel) {
        lfuCache.put(key(uid), channel);
        log.info("当前连接数:{}", lfuCache.size());
    }

    public Channel get(String uid) {
        return lfuCache.get(key(uid));
    }

    public void remove(String uid) {
        lfuCache.remove(key(uid));
    }

    public boolean containsKey(String uid) {
        return lfuCache.containsKey(key(uid));
    }

}
